package name.jautzy.esi.server;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import name.jautzy.esi.client.model.EsiShip;
import name.jautzy.esi.client.model.EsiShipFilter;
import name.jautzy.esi.client.model.Fit;
import name.jautzy.esi.client.service.FitService;
import name.jautzy.esi.server.model.FitFactory;
import name.jautzy.esi.server.model.FitProxy;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class FitServiceImpl extends RemoteServiceServlet implements
FitService {
	final private EdbDAO dao = new EdbDAO();
	
	public PagingLoadResult<EsiShip> getShips(EsiShipFilter filter) {
		List<EsiShip> ships = new LinkedList<EsiShip>();
		
		for (FitProxy proxy : dao.getFits(filter)) {
			ships.add(proxy.getEsiShip());
		}
		
		PagingLoadResult<EsiShip> ret = new BasePagingLoadResult<EsiShip>(ships, filter.getOffset(), filter.getCountResult());
		return ret;
	}

	@Override
	public EsiShip addShip(String eftFit, boolean pvp, boolean pve) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if (!userService.isUserLoggedIn())
			return null;
		User user = userService.getCurrentUser();
		FitFactory fact = new FitFactory(user.getEmail());
		fact.parseString(eftFit,dao);
		if (dao.fitExist(fact.getFitProxy().getFitId()))
			throw new IOException("Fit "+fact.getFitProxy().getName()+" already exist for Ship "+fact.getFitProxy().getShipName());
		fact.constructAll();
		fact.getFitProxy().setPve(pve);
		fact.getFitProxy().setPvp(pvp);
		dao.putFit(fact);
		return fact.getFitProxy().getEsiShip();
	}

	@Override
	public Fit getFit(String id) {
		Fit fit = dao.getFit(id);
		return fit;
	}

	@Override
	public void removeShips(List<String> ids) {
		UserService userService = UserServiceFactory.getUserService();
		dao.removeFits(ids,userService.getCurrentUser().getEmail());
	}

	@Override
	public void addFitUser(String fitId) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if (!userService.isUserLoggedIn())
			return;
		boolean result = dao.addFitUser(userService.getCurrentUser().getEmail(), fitId);
		if (!result)
			throw new IOException ("can't copy Fit");
	}

	@Override
	public void regenShip(String fitId) throws IOException {
		Fit fit = dao.getFit(fitId);
		FitFactory fact = new FitFactory(fit.getMaker());
		fact.parseString(fit.getEftFit(), dao);
		fact.constructAll();
		dao.putFit(fact.getFit());
		
	}

}
